package sqlexplorer.commands;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IViewReference;
import org.eclipse.ui.PlatformUI;

import sqlexplorer.application.ConnectionsController;
import sqlexplorer.application.exceptions.ConnectionFailedException;
import sqlexplorer.ui.views.ConnectionsView;

public class ConnectHandler extends AbstractHandler{
	
	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException{
		IViewReference[]iviews =PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getViewReferences();
		
		for(IViewReference viewReference:iviews){
			if(viewReference.getId().equals("sqlexplorer.ui.views.connectionsview")){
				ConnectionsView connectionView=(ConnectionsView)viewReference.getView(true);
				
				IStructuredSelection selection=(IStructuredSelection)connectionView.getViewer().getSelection();
				
				if(selection!=null) {
					int index = ConnectionsController.getInstance().getIndexForName((String)selection.getFirstElement());
					
					try{
						ConnectionsController.getInstance().connect(index);
					}catch(ConnectionFailedException exc){
						exc.printStackTrace();
					}
				}
			}
		}
		
		return null;
	}
}
